package Controller;

import java.io.*;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import Entity.Experiment;
import Service.ExperimentService;
import Service.SelectionService;


public class UploadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    // 上传文件存储目录
    private static final String UPLOAD_DIRECTORY = "WEB-INF" + File.separator + "upload";

    //设置上传解析字段大小临界值
    private static final int MEMORY_THRESHOLD   = 1024 * 1024 * 3;  // 60MB
    //设置上传文件大小的上界20MB
    private static final int MAX_FILE_SIZE      = 1024 * 1024 * 20; // 20MB
    //设置文件和表单数据大小和上界100MB
    private static final int MAX_REQUEST_SIZE   = 1024 * 1024 * 100; // 50MB

    /**
     * 上传数据及保存文件
     */
    @SuppressWarnings("finally")
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	
    	request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
    	
        // 检测是否为多媒体上传
        if (!ServletFileUpload.isMultipartContent(request)) {
            // 如果不是则停止
            PrintWriter writer = response.getWriter();
            writer.println("Error: 表单必须包含 enctype=multipart/form-data");
            writer.flush();
            return;
        }
        HttpSession session = request.getSession(false);
        
        String eid = null;
        String tid=null;
        String identity=null;
        String tname=null;
        String sid=null;
        //eid=request.getParameter("eid");
        //String tname=request.getParameter("tname");
        //String type=request.getParameter("identity");
        
        String uid = "t";
        uid=(String) session.getAttribute("uid");
        
        
//        System.out.println("eid:"+eid);
//        System.out.println("tname:"+tname);
//        System.out.println("identity:"+type);
        
        
        //表示身份 1 学生 2老师
  //      String identity=(String)request.getParameter("identity");
        
        
        // 配置上传参数
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // 设置解析字段时内存临界值 - 超过后将产生临时文件并存储于临时目录中
        factory.setSizeThreshold(MEMORY_THRESHOLD);
        // 设置临时存储目录
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

        ServletFileUpload upload = new ServletFileUpload(factory);

        // 设置最大文件上传值
        upload.setFileSizeMax(MAX_FILE_SIZE);

        // 设置最大请求值 (包含文件和表单数据)
        upload.setSizeMax(MAX_REQUEST_SIZE);

        // 中文处理
        upload.setHeaderEncoding("UTF-8");

        // 构造临时路径来存储上传的文件
        // 这个路径相对当前应用的目录
        //File.separator 表示系统默认路径分割字符，Windows下 / 和\ 都可；Linux则只能为/
//        String aaa="upload";
//        String op=request.getParameter("op");
//        if(op!=""||op!=null||op.equals("1")){//学生上传报告
//        	aaa="exp";
//        }
//        else{
//        	aaa="exmod";
//        }
        
        String uploadPath = getServletContext().getRealPath("/") + UPLOAD_DIRECTORY + File.separator;
        
        //文件名
        String Fname=null;
        
        try {
            // 解析请求的内容提取文件数据
            @SuppressWarnings("unchecked")
            List<FileItem> formItems = upload.parseRequest(request);
            if (formItems != null && formItems.size() > 0) {
                // 迭代表单数据
                for (FileItem item : formItems) {
                	String temp = "item,test"+item.getString()+"PARA";
                	String fname=item.getFieldName();
                	String final_ans = new String(temp.getBytes("iso-8859-1"), "utf-8");
                	//System.out.println("names:"+fname+"#");
                	if("eid".equals(fname)){
                		eid= new String((item.getString()).getBytes("iso-8859-1"), "utf-8");
                		//System.out.println("eid#"+eid);
                	}else if("tid".equals(fname)){
                		tid= new String((item.getString()).getBytes("iso-8859-1"), "utf-8");
                		//System.out.println("tid#"+tid);
                	}else if("tname".equals(fname)){
                		tname= new String((item.getString()).getBytes("iso-8859-1"), "utf-8");
                		//System.out.println("tname#"+tname);
                	}else if("identity".equals(fname)){
                		identity= new String((item.getString()).getBytes("iso-8859-1"), "utf-8");
                		//System.out.println("identity#"+identity);
                	}
                	else if("sid".equals(fname)){
                		sid=  new String((item.getString()).getBytes("iso-8859-1"), "utf-8") ;
                		//System.out.println("identity#"+identity); 
                	}
                	//System.out.println("###"+final_ans+"###");
                	
                    // 处理不在表单中的字段
                    if (!item.isFormField()) {
//                    	System.out.println("item,test"+item.getString());
//                    	String item_name = item.getName();
                    	//if (item_name.equals("file")) {
                    	
                    	//uid未学生id，先缺省为tid
                    	uid=tid;
                    	
                    	
                            String fileName = new File(item.getName()).getName();
                            String filePath = uploadPath + eid + "_" + uid + "_" + fileName;
                            Fname=eid+ "_" + uid + "_" + fileName;
                            File storeFile = new File(filePath);
                            // 在控制台输出文件的上传路径
                            System.out.println(filePath);
                            // 保存文件到硬盘
                            item.write(storeFile);
                            request.setAttribute("message",
                                    "文件上传成功!");	
                    	//}
//                    	else if (item_name.equals("eid")){
//                    		eid=item.g;
//                    	}
                    }
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
            request.setAttribute("message", "上传文件大小超出最大值！");
        } catch (Exception ex) {
            request.setAttribute("message",
                    "发生未知错误上传失败");
        }
        finally {
        	
        	//修改数据库的表
        	//老师
        	System.out.println("eid:"+eid);
        	System.out.println("tid:"+tid);
            System.out.println("tname:"+tname);
            System.out.println("identity:"+identity);
            System.out.println("filename:"+Fname);
            System.out.println(eid);
        	if("2".equals(identity)){
        		ExperimentService ser=new ExperimentService();
        		Experiment exp=null;
        		System.out.println(eid);
        		if(eid!=null&&eid!=""){
        		exp=ser.findExperimentById(Integer.parseInt(eid));
        		}
        		if(exp!=null)
        		exp.setTeURL(Fname);
        		ser.updateExperiment(exp);
        		System.out.println(Fname);
        	}else if("1".equals(identity)){
        		//学生上传报告
        		//tid tname eid sid
        		SelectionService ss = new SelectionService();
        		ss.uploadFile(Integer.parseInt(sid),Fname);
        	}
        	
     
        	
            // 跳转到 上传结果反馈界面message.jsp //identity uid
        	request.setAttribute("identity", identity);
        	request.setAttribute("tid", tid);
        	request.setAttribute("tname", tname);
            request.getRequestDispatcher("/WEB-INF/page/message.jsp?").forward(request, response);
            return;
        }
    }
}